package main

import (
	"net/http"
	"gxgeek.com/gxgeek/learngo/lang/errhangdlingdling/filelistingserver/filelisting"
	"os"
	"log"
	_"net/http/pprof"
)

type appHandler func(writer http.ResponseWriter, request *http.Request) error

type userError interface {
	error
	Message() string
}
func errorWrapper(handler appHandler) func(http.ResponseWriter, *http.Request) {
	return func(writer http.ResponseWriter, request *http.Request) {

		defer func() {
			r := recover()
			if r !=nil {
				log.Printf("panic:	%v ",r)
				http.Error(writer,
					http.StatusText(http.StatusInternalServerError),
					http.StatusInternalServerError)
			}
		}()
		err := handler(writer, request)
		if err != nil {
			log.Printf("Error handing request :%s",err.Error())
			code := http.StatusOK
			if userError, ok :=err.(userError); ok {
				http.Error(writer,userError.Message(),http.StatusBadRequest)
				return
			}
			switch  {
			case os.IsNotExist(err):
				code = http.StatusNotFound
			case os.IsPermission(err):
				code = http.StatusForbidden
			default:
				code = http.StatusInternalServerError
			}
			http.Error(writer,
				http.StatusText(code), code)
		}

	}
}

func main() {
	http.HandleFunc("/list/", errorWrapper(filelisting.HandleFileList))
	err := http.ListenAndServe(":8892", nil)
	if err != nil {
		panic(err)
	}
}
